﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HZ.BidSystem.Model.View;

public partial class Manage_BargainListExpert2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        CurrentAccount.CheckSessionTimeOut(this);
        if (!IsPostBack)
        {
            Bind();
            getExpertScoreCount();
            getIsSubmit();
        }
    }
    protected void pager1_PageChanging(object sender, HZ.Web.PageChaningEventArgs e)
    {
        Bind(); 
    }

    private void getIsSubmit()
    {
        string sql = string.Format(@"select ExpertPriceSubmitStatus2 from PB_BARGAINEXPERTPRICE where UserID='{0}' and ExpertPriceSubmitStatus2=1", CurrentAccount.Account.AccountName);
        DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(sql);
        if (dt.Rows.Count > 0)
        {
            btnAdd.Enabled = false;
            btnSubmit.Enabled = false;
        } 
    }

    private void getExpertScoreCount()
    {

        string sql = string.Format(@" select isnull(产品总数,0)产品总数,isnull(已给价产品数,0)已给价产品数,isnull(未给价产品数,0)未给价产品数 from 
        (select COUNT(distinct Company_Goods)  产品总数,UserID from PB_BARGAINEXPERTPRICE where UserID='{0}' and  [ExpertPriceNum]=2 group by UserID )a 
        left join 
        (select COUNT(distinct Company_Goods)  已给价产品数,UserID from PB_BARGAINEXPERTPRICE where UserID='{0}' and [ExpertPriceNum]=2 AND ISNULL([ExpertPriceFlag2],0)=1  group by UserID )b on a.UserID=b.UserID
        left join 
        (select COUNT(distinct Company_Goods) 未给价产品数,UserID from dbo.PB_BARGAINEXPERTPRICE where UserID='{0}' and [ExpertPriceNum]=2 AND ISNULL([ExpertPriceFlag2],0)=0  group by UserID  )c on a.UserID=c.UserID", CurrentAccount.Account.AccountName);
        DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(sql);
        if (dt.Rows.Count > 0)
        {
            lblExpertScoreCount.Text = dt.Rows[0]["产品总数"].ToString();
            lblScoredCount.Text = dt.Rows[0]["已给价产品数"].ToString();
            lblExpertScoreHad.Text = dt.Rows[0]["未给价产品数"].ToString(); 
        }
    }

    private void Bind()
    {
        int totalrecord;
        string append = "";
        if (ddlExpertPriceFlag.SelectedValue == "全部")
        {
             append = string.Format(@" UserID='{0}'  and  [ExpertPriceNum]=2", CurrentAccount.Account.AccountName);
        }
        else
        {
             append = string.Format(@" UserID='{0}'  and  [ExpertPriceNum]=2 and {1}", CurrentAccount.Account.AccountName, ddlExpertPriceFlag.SelectedValue);
        }
        //var bidprice = BLL_Factory.IBLL_Company.GetBidPrice(new HZ.BidSystem.Model.QBidPrice() { SortFields = "GoodsId", ProductName = txtProductName.Text.Trim(), MedicineModel = txtMedicineModel.Text.Trim(), Outlookc = txtOutlookc.Text.Trim(), CompanyName_Sc = txtCompanyName_sc.Text.Trim(), Append = append }, pager1.CurrentPage, pager1.PageSize, out totalrecord);
        DataTable dt = BLL_Factory.IBLL_Company.GetExpertPrice2(new HZ.BidSystem.Model.QBidPrice() { SortFields = "Company_Goods", ProductName = txtProductName.Text.Trim(), ModelSmall = txtModel.Text.Trim(), Outlookc = txtOutlookc.Text.Trim(), CompanyName_Sc = txtCompanyName_sc.Text.Trim(), Append = append }, pager1.CurrentPage, pager1.PageSize, out totalrecord);
        pager1.RecordCount = totalrecord;
        gv1.DataSource = dt;
        gv1.DataBind();
    }
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        pager1.CurrentPage = 1;
        Bind();
    }
    protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gv1.EditIndex = e.NewEditIndex;
        Bind();
    }
    protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Reset the edit index.
        gv1.EditIndex = -1;

        GridViewRow row = gv1.Rows[e.RowIndex];
        string Company_Goods = new HZ.Common.ConvertHelper(row.Cells[0].Text).ToString();

        var newlimitprice = new HZ.Common.ConvertHelper((row.FindControl("txtLitmit") as TextBox).Text).ToDouble.Value;
        //Bind data to the GridView control.
        BLL_Factory.IBLL_Manage.UpdateLimitPrice(Company_Goods, newlimitprice);
        Bind();


    }
    protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        gv1.EditIndex = -1;
        //Bind data to the GridView control.
        Bind();

    }

    protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)//前台已绑定投标企业名称
        //{
        //    var lbl = e.Row.FindControl("lblCompanyId_Tb") as Label;
        //    lbl.Text = HZ.BidSystem.BLL.BLL_Cache.CompanyCache[int.Parse(lbl.Text)].CompanyName;
        //}
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //用于记录高于限价的药品条数
        int count = 0;
        //取值
        DataTable priceTable = new DataTable();
        priceTable.Columns.Add("Price");
        priceTable.Columns.Add("Company_Goods");
        priceTable.Columns.Add("UserID");
        foreach (GridViewRow row in gv1.Rows)
        {
            //保存当页填写数据
            TextBox txt_ExpertPrice1 = row.FindControl("txt_ExpertPrice1") as TextBox;
            //如果未填价格直接跳过
            if (string.IsNullOrEmpty(txt_ExpertPrice1.Text.Trim()))
            {
                continue;
            }
            //专家填写价格
            decimal price = 0;

            //获取页面限价 
            decimal limitedprice = 0;
             
            if (Decimal.TryParse(txt_ExpertPrice1.Text, out price) && price <= 0)
            {
                continue;
            }
            //判断是否高于限价

            if (Decimal.TryParse((row.FindControl("lbllimitedprice") as Label).Text, out limitedprice) && price > limitedprice)
            {
                count++;
                continue;
            }
            string company_goods = (row.FindControl("lblcg") as Label).Text;
            priceTable.Rows.Add(new object[] { price, company_goods, CurrentAccount.Account.AccountName });

        }
        if (priceTable.Rows.Count == 0)
        {
            Bind();
            return;
        }
        //专家第一轮报价
        int result = BLL_Factory.IBLL_Company.UpdateBargainPriceBatch(priceTable, 2);
        if (result > 0)
        {
            HZ.Web.WebUtil.Alert("保存成功!");
            HZ.Web.WebUtil.RedirectByScript("BargainListExpert2.aspx");
            getExpertScoreCount();
            if (count > 0)
            {
                HZ.Web.WebUtil.Alert("有" + count + "条药品高于建议价限价被跳过!");
            }
        }
        else
        {
            HZ.Web.WebUtil.Alert("保存失败!");
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int result = BLL_Factory.IBLL_Company.ExpertPriceSubmit(CurrentAccount.Account.AccountName, 2);
        if (result == 3)
        {
            HZ.Web.WebUtil.Alert("不能重复提交!");
            HZ.Web.WebUtil.RedirectByScript("BargainListExpert2.aspx");
            return;
        }
        if (result == -1)
        {
            HZ.Web.WebUtil.Alert("您还有部分药品未给价,请完成后再试!");
            return;
        }
        if (result == 0)
        {
            HZ.Web.WebUtil.Alert("提交出错,请联系工作人员!");
            return;
        }
        if (result == 1)
        {
            HZ.Web.WebUtil.Alert("提交成功!");
            HZ.Web.WebUtil.RedirectByScript("BargainListExpert2.aspx");
            return;
        }
    }


    /// <summary>
    /// 专家同意企业还价
    /// </summary> 
    protected void LinkButtonGet_Click(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        if (btn.CommandName == "Yes")
        {

            string bidId = btn.CommandArgument.Split(',')[0];
            string UserID = btn.CommandArgument.Split(',')[1];
            int ExpertState = 1;
            int CheckSecces = BLL_Factory.IBLL_Company.UpdateBarinPrice2Argee(ExpertState, bidId, UserID);
            if (CheckSecces == 1)
            {
                HZ.Common.log4netManager.LogInfo("专家同意企业还价", string.Format("专家同意企业还价：专家编号：{0},报价产品：{1}", CurrentAccount.Account.AccountName, bidId), null);
                HZ.Web.WebUtil.Alert("操作成功！", this);
                Bind();
            }
            else if (CheckSecces == 3)
            {
                HZ.Web.WebUtil.Alert("企业报价已高于上限价，同意失败！", this);
            }
            else 
            {
                HZ.Web.WebUtil.Alert("操作失败，请检查数据！", this);
            }
        }
    }
    /// <summary>
    /// 判断文本框是否可用
    /// </summary>
    /// <param name="expertState"></param>
    /// <returns></returns>
    public bool getEnabled(object expertState) 
    {
        bool Enabled = false;
        if (expertState.ToString() == "1") 
        {
            Enabled = false;
        }
        else if (expertState.ToString() == "0")
        {
            Enabled = false;
        }
        else if (expertState.ToString() == "2")
        {
            Enabled = true;
        }
        else 
        {
            Enabled = false;
        }
        return Enabled;
    }

    /// <summary>
    /// 专家不同意企业还价
    /// </summary> 
    protected void LinkButtonUNGet_Click(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        if (btn.CommandName == "No")
        {
            string bidId = btn.CommandArgument.Split(',')[0];
            string UserID = btn.CommandArgument.Split(',')[1];
            int ExpertState =2;
            int CheckSecces = BLL_Factory.IBLL_Company.UpdateBarinPrice2Argee(ExpertState, bidId, UserID);
            if (CheckSecces == 1)
            {
                HZ.Common.log4netManager.LogInfo("专家不同意企业还价", string.Format("专家不同意企业还价：专家编号：{0},报价产品：{1}", CurrentAccount.Account.AccountName, bidId), null);
                HZ.Web.WebUtil.Alert("操作成功！", this);
                Bind();
            }
            else
            {
                HZ.Web.WebUtil.Alert("操作失败，请检查数据！", this);
            }
        }
    }

    /// <summary>
    /// 显示限价价格
    /// </summary> 
    //protected void LinkButtonPrice_Click(object sender, EventArgs e)
    //{
    //    LinkButton btn = (LinkButton)sender;
    //    if (btn.CommandName == "SELECT")
    //    {
    //        string bidId = btn.CommandArgument.Split(',')[0];
    //        string SortID = btn.CommandArgument.Split(',')[1];
    //        ViewState["SortID"] = SortID;
    //        ViewState["bidId"] = bidId;
    //        PriceSelect.Visible = true;
    //        BindData(ViewState["bidId"].ToString());
    //        BindPrice(ViewState["SortID"].ToString());
    //        //int CheckSecces = BLL_Factory.IBLL_Company.UpdateBarinPrice2Argee(ExpertState, bidId, UserID);
    //        //if (CheckSecces == 1)
    //        //{
    //        //    HZ.Common.log4netManager.LogInfo("专家同意企业还价", string.Format("企业确认第二轮价格：专家编号：{0},报价产品：{1}", CurrentAccount.Account.AccountName, bidId), null);
    //        //    HZ.Web.WebUtil.Alert("操作成功！", this);
    //        //    Bind();
    //        //}
    //        //else
    //        //{
    //        //    HZ.Web.WebUtil.Alert("操作失败，请检查数据！", this);
    //        //}
    //    }
    //}
    //参考价格
    //private void BindData(string bidId)
    //{

    //    string Company_goods = bidId;
    //    DataTable dt = BLL_Factory.IBLL_Company.GetMinprie(Company_goods);
    //    if (dt.Rows.Count > 0)
    //    {
    //        lbQGBidPrice.Text = dt.Rows[0]["QGBidPrice"].ToString();
    //        lbQGBidPrice2.Text = dt.Rows[0]["QGBidPrice2"].ToString();
    //        lbHosMinPrice.Text = dt.Rows[0]["HosMinPrice"].ToString();
    //        lbJkMinPrice.Text = dt.Rows[0]["JkMinPrice"].ToString();
    //        lbDiCengPrice.Text = dt.Rows[0]["DiCengPrice"].ToString();

    //    }
    //}
    //同招标单元拟中标价
    //private void BindPrice(string SortID)
    //{
    //    int totalrecord = 0;
    //    DataTable dt = BLL_Factory.IBLL_Company.GetSortGoodsPrice(SortID, 1, 0, out totalrecord);
    //    gv2.DataSource = dt;
    //    gv2.DataBind();
    //}


}
